"""
智能简历分析系统 - 主应用
基于RAG和Agent的智能招聘平台
"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import logging
import os

# 导入配置
from config import Config

# 导入工具模块
from utils.database import DatabaseManager
from utils.file_utils import FileUtils

# 导入业务模块
from resume_processor import ResumeProcessor

# 导入RAG系统
from rag_system.vector_store import VectorStore
from rag_system.retriever import RAGRetriever

# 导入Agent系统
from agent_system.recruiter_agent import RecruiterAgent
from agent_system.analyzer_agent import AnalyzerAgent
from agent_system.advisor_agent import AdvisorAgent

# 导入API蓝图
from api.auth import auth_bp
from api.resume import resume_bp
from api.rag import rag_bp
from api.agent import agent_bp

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 配置应用
    app.config.from_object(Config)
    
    # 启用CORS
    CORS(app)
    
    # 验证配置
    Config.validate_config()
    
    # 初始化数据库
    db = DatabaseManager()
    db.init_database()
    
    # 初始化RAG系统
    vector_store = VectorStore()
    rag_retriever = RAGRetriever(vector_store)
    
    # 初始化Agent系统
    recruiter_agent = RecruiterAgent(rag_retriever)
    analyzer_agent = AnalyzerAgent(rag_retriever)
    advisor_agent = AdvisorAgent()
    
    # 初始化技能数据
    from knowledge_base.skill_database import SkillDatabase
    skill_db = SkillDatabase()
    for skill in skill_db.get_all_skills():
        vector_store.add_skill(
            skill_id=skill["id"],
            skill_name=skill["name"],
            description=skill["description"],
            metadata={
                "category": skill["category"],
                "level": skill["level"],
                "tags": ", ".join(skill["tags"])
            }
        )
    
    # 注册蓝图
    app.register_blueprint(auth_bp)
    app.register_blueprint(resume_bp)
    app.register_blueprint(rag_bp)
    app.register_blueprint(agent_bp)
    
    # 健康检查
    @app.route('/api/health')
    def health_check():
        return jsonify({
            'status': 'healthy',
            'version': '1.0.0',
            'features': ['RAG', 'Agent', 'Resume Analysis']
        })
    
    # 全局错误处理
    @app.errorhandler(404)
    def not_found(error):
        return jsonify({'error': '接口不存在'}), 404
    
    @app.errorhandler(500)
    def internal_error(error):
        return jsonify({'error': '服务器内部错误'}), 500
    
    logger.info("应用初始化完成")
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=Config.DEBUG
    )
